/*
* websocket
*/

import { type } from "@/utils/index";
class WebSocketObj {
    constructor(url, funObj, vue) {
        //ws参数 
        this.url = url;
        this.ws = null;//建立的连接
        this.lockReconnect = false;//是否真正建立连接
        this.timeout = 5 * 1000;//58秒一次心跳
        this.timeoutObj = null;//心跳倒计时 
        this.timeoutnum = null;//断开 重连倒计时
        this.funObj = funObj; //外部接收消息函数 
        this.vue = vue
        this.initWebSocket(this.url)
        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        // window.onbeforeunload = that.onbeforeunload
    }
    initWebSocket(url) {
        this.ws = new WebSocket(url);
        this.ws.onopen = this.onopen.bind(this);
        this.ws.onmessage = this.onmessage.bind(this);
        this.ws.onclose = this.onclose.bind(this);
        this.ws.onerror = this.onerror.bind(this);

    }
    onopen() {
        // console.log("连接websocket");
        this.start();
        this.funObj.onopen()
    }
    reconnect() {//重新连接

        // console.log('本机断开');
        this.vue.$bus.$emit("nativeStatus", true);
        let that = this;
        if (that.lockReconnect) {
            return;
        }
        // that.initWebSocket();
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        that.timeoutNum && clearTimeout(that.timeoutNum);
        that.timeoutNum = setTimeout(function () {
            //新连接
            that.initWebSocket(that.url);
            that.lockReconnect = false;
        }, 5000);
    }
    start() { //开启心跳 
        // console.log('开启心跳');
        let self = this;
        if (self.ws && self.ws.readyState == 1) {
            this.vue.$bus.$emit("nativeStatus", false);
            self.ws.send("ping");
        } else {
            self.reconnect();
        }
        //清除延时器
        self.timeoutObj && clearInterval(self.timeoutObj);
        self.timeoutObj = setInterval(() => {
            console.log('心跳', self.ws, new Date());
            if (self.ws && self.ws.readyState == 1) {
                self.ws.send("ping"); //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
            } else {
                // if (self.ws.readyState != 1) debugger;
                self.reconnect();
            }
        }, self.timeout);
    }
    onmessage(e) {
        // console.log('接收数据', e)
        //处理数据的地方
        if (e.isTrusted && type(e.data)) {
            let data = JSON.parse(e.data);
            this.funObj.onmessage(data)
        }

    }
    onclose(e) {
        console.log('websocket 断开: ', e);
        // if (this.exitIsClose) {
        //     this.timeoutObj && clearTimeout(this.timeoutObj);
        //     this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        //     this.timeoutNum && clearTimeout(this.timeoutNum);
        // }
    }
    onerror(e) {
        console.log("出现错误", new Date());
        //重连  
        // if (this.ws.readyState != 1) debugger;
        this.reconnect();
    }
    wsDestroy() {
        console.log("beforeDestroy");
        this.ws.close();
        clearInterval(this.timeoutObj);
    }

}


export default WebSocketObj